package org.millioncall.yueyoga.admin.action;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.millioncall.openplatform.common.Pager;
import org.millioncall.openplatform.common.PaginatedList;
import org.millioncall.openplatform.util.StringUtils;
import org.millioncall.openplatform.util.WebAppUtils;
import org.millioncall.yueyoga.admin.model.ClassScheduleModel;
import org.millioncall.yueyoga.admin.model.MemberModel;
import org.millioncall.yueyoga.admin.model.Reservation;
import org.millioncall.yueyoga.admin.model.TinyClass;
import org.millioncall.yueyoga.admin.model.User;
import org.millioncall.yueyoga.admin.service.CheduleService;
import org.millioncall.yueyoga.admin.service.ClazzService;
import org.millioncall.yueyoga.admin.service.MemberService;
import org.millioncall.yueyoga.admin.service.ReservationService;
import org.millioncall.yueyoga.admin.service.hessian.ReserveLessianService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;

/**
 * 前端快速预定课程信息 created by lishoujing on 2014-06-21 16:05:23
 */
@Controller
public class ReservateAction extends BaseAction {
	private static final Logger LOGGER = LoggerFactory.getLogger(ReservateAction.class);

	private MemberService memberService;
	private CheduleService cheduleService;
	private ReservationService reservationService;
	private ClazzService clazzService;

	@Resource(name = "testReserveSeatService")
	private ReserveLessianService testReserveSeatService;

	public void setMemberService(MemberService memberService) {
		this.memberService = memberService;
	}

	public void setReservationService(ReservationService reservationService) {
		this.reservationService = reservationService;
	}

	public ReservationService getReservationService() {
		return reservationService;
	}

	public void setCheduleService(CheduleService cheduleService) {
		this.cheduleService = cheduleService;
	}

	public void setClazzService(ClazzService clazzService) {
		this.clazzService = clazzService;
	}

	/**
	 * 进入前台订座界面
	 * 
	 * @param map
	 */
	@RequestMapping(value = "/seat.jhtml")
	public String toFrontReservation(Integer pageNo, Integer pageSize, HttpServletRequest request,
			HttpServletResponse response, ModelMap model) {
		initFrontHeader(request, model);
		Map<String, Object> map = new HashMap<String, Object>();
		User user = super.getUser(request);
		map.put("hallcode", user.getOrganizationId());
		List<TinyClass> clazzList = this.clazzService.findAllClassTiny(map);
		model.put("clazzList", clazzList);

		return "reservation_main";
	}

	/**
	 * 查询在店会员
	 */
	@RequestMapping(value = "/ajaxGetPresentMembers.jhtml", method = RequestMethod.POST)
	public void ajaxGetPresentMembers(HttpServletRequest request, HttpServletResponse response, ModelMap model,
			Integer pageNo, Integer pageSize) {
		initFrontHeader(request, model);

		Map<String, Object> map = new HashMap<String, Object>();
		User user = this.getUser(request);
		map.put("hallcode", user.getOrganizationId());
		map.put("findType", "present");

		Date today = new Date();

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

		try {
			map.put("timeRangeStart", sdf.parse(sdf.format(today)));
		} catch (ParseException e) {
			LOGGER.error("日期解析异常", e);
		}
		Calendar can = Calendar.getInstance();
		can.setTime(today);
		can.add(Calendar.DAY_OF_MONTH, 1);

		try {
			map.put("timeRangeEnd", sdf.parse(sdf.format(can.getTime())));
		} catch (ParseException e) {
			LOGGER.error("日期解析异常", e);
		}

		sdf = new SimpleDateFormat("HH:mm");
		map.put("timeLimit", sdf.format(today));

		int start = 0;
		int limit = 10;
		if (pageSize != null) {
			limit = pageSize;
		}
		if (pageNo != null) {
			start = (pageNo - 1) * limit;
		}

		PaginatedList<MemberModel> memberList = memberService.findFrontPresentMemberList(start, limit, map);
		Pager pager = memberList.getPager();
		String memberItems = JSON.toJSONStringWithDateFormat(memberList, "yyyy-MM-dd",
				SerializerFeature.WriteDateUseDateFormat);
		String json = "{'success':true,totalPages:" + pager.getCountOfTotalPages() + ",totalItems:"
				+ pager.getCountOfTotalResults() + ",pageNo:" + pager.getPageNo() + ",pageSize:" + pager.getPageSize()
				+ ",prevPageNo:" + pager.getPrevPageNo() + ",nextPageNo:" + pager.getNextPageNo() + ",items:"
				+ memberItems + "}";
		WebAppUtils.ajaxResponse(response, json);
	}

	/**
	 * 查询离店会员
	 */
	@RequestMapping(value = "/ajaxGetAbsentMembers.jhtml", method = RequestMethod.POST)
	public void ajaxGetAbsentMembers(HttpServletRequest request, HttpServletResponse response, ModelMap model,
			Integer pageNo, Integer pageSize) {
		initFrontHeader(request, model);

		Map<String, Object> map = new HashMap<String, Object>();
		User user = this.getUser(request);
		map.put("hallcode", user.getOrganizationId());
		map.put("findType", "absent");

		Date today = new Date();

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

		try {
			map.put("timeRangeStart", sdf.parse(sdf.format(today)));
		} catch (ParseException e) {
			LOGGER.error("日期解析异常", e);
		}
		Calendar can = Calendar.getInstance();
		can.setTime(today);
		can.add(Calendar.DAY_OF_MONTH, 1);

		try {
			map.put("timeRangeEnd", sdf.parse(sdf.format(can.getTime())));
		} catch (ParseException e) {
			LOGGER.error("日期解析异常", e);
		}

		sdf = new SimpleDateFormat("HH:mm");
		map.put("timeLimit", sdf.format(today));

		int start = 0;
		int limit = 10;
		if (pageSize != null) {
			limit = pageSize;
		}
		if (pageNo != null) {
			start = (pageNo - 1) * limit;
		}

		PaginatedList<MemberModel> memberList = memberService.findFrontAbsentMemberList(start, limit, map);
		Pager pager = memberList.getPager();
		String memberItems = JSON.toJSONStringWithDateFormat(memberList, "yyyy-MM-dd",
				SerializerFeature.WriteDateUseDateFormat);
		String json = "{'success':true,totalPages:" + pager.getCountOfTotalPages() + ",totalItems:"
				+ pager.getCountOfTotalResults() + ",pageNo:" + pager.getPageNo() + ",pageSize:" + pager.getPageSize()
				+ ",prevPageNo:" + pager.getPrevPageNo() + ",nextPageNo:" + pager.getNextPageNo() + ",items:"
				+ memberItems + "}";
		WebAppUtils.ajaxResponse(response, json);

	}

	/** 查询所属会馆所有的会员的信息 */
	@RequestMapping(value = "/ajaxGetMemberInfoList.jhtml")
	public void ajaxGetMemberInfoList(Integer pageNo, Integer pageSize, String cardNumber, HttpServletRequest request,
			HttpServletResponse response, ModelMap model) {
		initFrontHeader(request, model);
		Map<String, Object> map = new HashMap<String, Object>();
		User user = this.getUser(request);
		map.put("cardNumber", cardNumber);
		map.put("hallcode", user.getOrganizationId());

		int start = 0;
		int limit = 10;
		if (pageSize != null) {
			limit = pageSize;
		}
		if (pageNo != null) {
			start = (pageNo - 1) * limit;
		}

		PaginatedList<MemberModel> memberList = memberService.findFrontMemberList(start, limit, map);
		Pager pager = memberList.getPager();
		String memberItems = JSON.toJSONStringWithDateFormat(memberList, "yyyy-MM-dd",
				SerializerFeature.WriteDateUseDateFormat);
		String json = "{'success':true,totalPages:" + pager.getCountOfTotalPages() + ",totalItems:"
				+ pager.getCountOfTotalResults() + ",pageNo:" + pager.getPageNo() + ",pageSize:" + pager.getPageSize()
				+ ",prevPageNo:" + pager.getPrevPageNo() + ",nextPageNo:" + pager.getNextPageNo() + ",items:"
				+ memberItems + "}";
		WebAppUtils.ajaxResponse(response, json);
	}

	/** 查询会员的信息 */
	@RequestMapping(value = "/ajaxGetMemberInfo.jhtml")
	public void ajaxGetMemberInfo(String memberId, HttpServletRequest request, HttpServletResponse response,
			ModelMap model) {
		initFrontHeader(request, model);
		String json = "{'success':false, 'items':'获取数据失败!'}";
		Map<String, Object> map = new HashMap<String, Object>();

		if (StringUtils.isNotBlank(memberId)) {
			User user = this.getUser(request);
			map.put("hallcode", user.getOrganizationId());
			map.put("id", memberId);

			MemberModel member = memberService.findFrontMemberDetailInfo(map);
			json = "{'success':true, 'items':'"
					+ JSON.toJSONStringWithDateFormat(member, "yyyy-MM-dd", SerializerFeature.WriteDateUseDateFormat)
					+ "'}";
		}
		WebAppUtils.ajaxResponse(response, json);
	}

	/** 获取所有座位信息 */
	@RequestMapping(value = "/ajaxGetSeatList.jhtml")
	public void ajaxGetSeatInfoList(String scheduleTime, HttpServletRequest request, HttpServletResponse response,
			ModelMap model) {
		initFrontHeader(request, model);
		String json = "{'success':false, 'items':'获取数据失败!'}";

		WebAppUtils.ajaxResponse(response, json);
	}

	/** 获取某个座位的信息 */
	@RequestMapping(value = "/ajaxGetSeatList.jhtml")
	public void ajaxGetSeatInfoDetail(Integer resvId, HttpServletRequest request, HttpServletResponse response,
			ModelMap model) {
		initFrontHeader(request, model);
		String json = "{'success':false, 'items':'获取数据失败!'}";
		if (resvId != null) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("ydId", resvId);
			List<Reservation> reservationList = reservationService.findReservationByCdts(map);
			json = "{'success':true, 'items':'" + JSON.toJSONString(reservationList) + "'}";
		}
		WebAppUtils.ajaxResponse(response, json);
	}

	/** 获取两个星期的日期 */
	@RequestMapping(value = "/ajaxGetTwoWeekDate.jhtml")
	public void ajaxGetTwoWeekDate(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
		initFrontHeader(request, model);
		String json = "{'success':false, 'items':'获取数据失败!'}";
		List<String> weekDateList = reservationService.findTwoWeekDate();
		json = JSON.toJSONString(weekDateList);
		WebAppUtils.ajaxResponse(response, json);
	}

	/** 根据日期获取课程信息 */
	@RequestMapping(value = "/ajaxGetScheduleListByDate.jhtml")
	public void ajaxGetTScheduleList(String clazzId, String kcrq, String memberId, HttpServletRequest request,
			HttpServletResponse response, ModelMap model) {
		initFrontHeader(request, model);
		String json = "{'success':false, 'items':'获取数据失败!'}";
		User user = getUser(request);
		if (StringUtils.isNotBlank(kcrq)) {
			List<ClassScheduleModel> csmList = cheduleService.findScheduleInfoList(clazzId, kcrq,
					user.getOrganizationId(), memberId);
			json = "{'success':true, 'items':'" + JSON.toJSONString(csmList) + "'}";
		}
		WebAppUtils.ajaxResponse(response, json);
	}

	/** 根据日期获取当前课程信息 */
	@RequestMapping(value = "/ajaxGetNowScheduleList.jhtml")
	public void ajaxGetNowScheduleList(String clazzId, HttpServletRequest request, HttpServletResponse response,
			ModelMap model) {
		initFrontHeader(request, model);
		String json = "{'success':false, 'items':'获取数据失败!'}";
		User user = getUser(request);
		List<ClassScheduleModel> csmList = cheduleService.findNowScheduleInfoList(clazzId, user.getOrganizationId());
		json = "{'success':true, 'items':'" + JSON.toJSONString(csmList) + "'}";
		WebAppUtils.ajaxResponse(response, json);
	}

	/** 根据条件预定课程 */
	@RequestMapping(value = "/ajaxResvSchedule.jhtml")
	public void ajaxResvSchedule(String scheId, String memberId, HttpServletRequest request,
			HttpServletResponse response, ModelMap model) {
		initFrontHeader(request, model);
		String json = "{'success':false, 'msg':'预定课程失败!'}";
		if (StringUtils.isBlank(scheId) || StringUtils.isBlank(memberId)) {
			WebAppUtils.ajaxResponse(response, json);
			return;
		}
		int rtv = reservationService.resvSchedule(scheId, memberId);
		String msg = "";
		boolean flag = false;
		if (rtv == 1) {
			msg = "预约成功!";
			flag = true;
		} else if (rtv == 2) {
			msg = "不能重复预约!";
		} else if (rtv == 3) {
			msg = "已超过产品的周预约次数限制";
		} else {
			msg = "预约失败!";
		}
		json = "{'success':" + flag + ", 'msg':'" + msg + "'}";
		WebAppUtils.ajaxResponse(response, json);
	}

	/** 根据条件查询预定的课程 */
	@RequestMapping(value = "/ajaxResvScheduleList.jhtml")
	public void ajaxResvScheduleList(String clazzId, String date, String memberId, HttpServletRequest request,
			HttpServletResponse response, ModelMap model) {
		initFrontHeader(request, model);
		String json = "{'success':false, 'items':'获取数据失败!'}";
		if (StringUtils.isBlank(date) || StringUtils.isBlank(memberId)) {
			WebAppUtils.ajaxResponse(response, json);
			return;
		}
		User user = getUser(request);
		List<ClassScheduleModel> csmList = cheduleService.findPersonScheduleList(clazzId, date, memberId,
				user.getOrganizationId());
		json = "{'success':true, 'items':'" + JSON.toJSONString(csmList) + "'}";
		WebAppUtils.ajaxResponse(response, json);
	}

	/** 根据条件查询出席的课程 */
	@RequestMapping(value = "/ajaxAttendScheduleList.jhtml")
	public void ajaxAttendScheduleList(String clazzId, String date, String memberId, HttpServletRequest request,
			HttpServletResponse response, ModelMap model) {
		initFrontHeader(request, model);
		String json = "{'success':false, 'items':'获取数据失败!'}";
		if (StringUtils.isBlank(date) || StringUtils.isBlank(memberId)) {
			WebAppUtils.ajaxResponse(response, json);
			return;
		}
		User user = getUser(request);
		List<ClassScheduleModel> csmList = cheduleService.findAttendScheduleList(clazzId, date, memberId,
				user.getOrganizationId());
		json = "{'success':true, 'items':'" + JSON.toJSONString(csmList) + "'}";
		WebAppUtils.ajaxResponse(response, json);
	}

	/** 根据条件取消预定的课程 */
	@RequestMapping(value = "/ajaxCancelSchedule.jhtml")
	public void ajaxCancelSchedule(String scheduleId, String memberId, HttpServletRequest request,
			HttpServletResponse response, ModelMap model) {
		String json = "{'success':true, 'msg':'取消预约失败!'}";
		if (StringUtils.isBlank(scheduleId) || StringUtils.isBlank(memberId)) {
			WebAppUtils.ajaxResponse(response, json);
			return;
		}
		boolean flag = reservationService.cancelResvSchedule(scheduleId, memberId);
		if (flag) {
			json = "{'success':true, 'msg':'取消预约成功!'}";
		}
		WebAppUtils.ajaxResponse(response, json);
	}

	/** 根据id出席课程 */
	@RequestMapping(value = "/ajaxAttendSchedule.jhtml")
	public void ajaxAttendSchedule(String resvId, Integer prId, HttpServletRequest request,
			HttpServletResponse response, ModelMap model) {
		String json = "{'success':false, 'msg':'出席失败!'}";
		User user = getUser(request);
		if (StringUtils.isBlank(resvId) || prId == null || prId == 0) {
			WebAppUtils.ajaxResponse(response, json);
			return;
		}
		json = reservationService.attendSchedule(resvId, prId, user);
		WebAppUtils.ajaxResponse(response, json);
	}

	/** 根据id取消出席课程 */
	@RequestMapping(value = "/ajaxCancelAttendSchedule.jhtml")
	public void ajaxCancelAttendSchedule(String resvId, Integer prId, HttpServletRequest request,
			HttpServletResponse response, ModelMap model) {
		String json = "{'success':true, 'msg':'取消失败!'}";
		if (StringUtils.isBlank(resvId) || prId == null || prId == 0) {
			WebAppUtils.ajaxResponse(response, json);
			return;
		}
		if (reservationService.cancelAttendSchedule(resvId, prId)) {
			json = "{'success':true, 'msg':'取消出席成功!'}";
		}
		WebAppUtils.ajaxResponse(response, json);
	}
}
